<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title></title>
	<style>
		html, body { margin: 0; padding: 0; font-size: 14px; }
		.fileinfoBlock { width: 260px; height: 36px; display: inline-block; padding: 2px; margin: 0 4px 0px 0; background-color: #e3eaf4; }
		.fileinfoBlock .icon { width: 36px; height: 36px; float: left; }
		.fileinfoBlock .center { width: 220px;  float: left; margin: 0 2px; }
		.fileinfoBlock .filename { font-size: 12px; float: left; color: #666; }
		.fileinfoBlock .operater { font-size: 12px; float: right; cursor: pointer; }
		.fileinfoBlock .filesize { font-size: 12px; color: #B0B0B0; }
		progress { display: block; width: 100%; height: 4px;}
		
		#topbar { position: fixed; top: 0px; left: 0px; width: 100%; padding:10px; background-color: #fff; border-bottom: 1px solid #eee; }
		#filescontainer { margin-top: 45px; padding: 10px }
	</style>
	<!-- <script src="js/vue.js"></script> -->
	<script src="js/vue.min.js"></script>
</head>
<body>
	<div id="up">
		<div id="topbar">
			<input id="fileToUpload" type="file" multiple v-on:change="selected" style="width: 70px;"> 
			<button v-on:click="upload">上传</button>
			<button v-on:click="clear">全删</button>
		</div>
		<div id="filescontainer">
			<file-info v-for="file in fileinfos" 
				v-bind:key="file.length" 
				v-bind:file="file"
				v-on:remove="removeFileInfo"
			></file-info>
		</div>
		<div v-show="debug" v-for="n in completednames">{{n}}</div>
	</div>
	<script>
		var paramVal = {
			methods: {
				getUrlParam: function(paraName) {
					var url = document.location.toString();
					var arrObj = url.split("?");
					if (arrObj.length > 1) {
						var arrPara = arrObj[1].split("&");
						var arr;
						for (var i = 0; i < arrPara.length; i++) {
							arr = arrPara[i].split("=");
							if (arr != null && arr[0] == paraName) {
								return arr[1] != undefined ? arr[1] : "";
							}
						}
						return "";
					}
					else {
						return "";
					}
				}
			}
		};
		
		var up = new Vue({
			el: '#up',
			data:{
				uploadURL: "/f",		//上传路径
				deleteURL: "/f/r",		//删除路径
				request: null,			//请求的XMLHttpRequest实例
				currentFileinfo: null,	//当前上传文件信息
				fileinfos: [],			//文件信息
				completednames: [],		//已完成的文件名称
				count: 0,				//上传计数，当前已上传到第几个文件
				debug: false,			//调试模式
				callback: "",			//父页面回调方法
				picscale: {				//图片等比例缩放
					scale: false,		//是否缩放
					maxwidth: 1440,		//最大宽度
					maxheight: 1080		//最大高度
				},			
			},
			mixins: [paramVal],
			created: function() {
				this.request = new XMLHttpRequest();
				this.request.upload.addEventListener("progress", this._uploadProgress, false);
				this.request.addEventListener("load", this._uploadComplete, false);
				this.request.addEventListener("abort", this._uploadCanceled, false);
				this.callback = this.getUrlParam("callback");
				if(this.getUrlParam("picscale") == "true") {
					this.picscale.scale = true;
					this.picscale.maxwidth = this.getUrlParam("maxwidth") != "" ? this.getUrlParam("maxwidth") : this.picscale.maxwidth;
					this.picscale.maxheight = this.getUrlParam("maxheight") != "" ? this.getUrlParam("maxheight") : this.picscale.maxheight;
				}
				
			},
			methods:{
				selected: function(event) {
					var files = event.target.files;
					for(var i = 0; i < files.length; i++) {
						this.fileinfos.push({
							file: files[i],
							name: files[i].name,
							size: files[i].size,
							percentComplete: '',
							complete: false,
							sequence: null
						});
					}
					//避免第二次与第一次选择相同的文件onchange不生效的问题
					event.target.value = null;
				},
				upload: function(event) {
					this._upload();
				},
				_upload: function() {
					//计数等于文件长度后停止上传
					if(this.count == this.fileinfos.length) {
						return;
					}
					this.currentFileinfo = this.fileinfos[this.count];
					//上传计数+1
					this.count++;
					var fd = new FormData();
					fd.append("file", this.currentFileinfo.file);
					//发送请求，上传文件
					var url = this.uploadURL;
					if(this.picscale.scale) {
						url += "?picscale=" + this.picscale.scale + "&maxwidth=" + this.picscale.maxwidth + "&maxheight=" + this.picscale.maxheight;	
					}
					this.request.open("POST", url);
					this.request.send(fd);
				},
				_uploadProgress: function(event){
					if(event.lengthComputable) {
						this.currentFileinfo.percentComplete = Math.round(event.loaded * 100 / event.total);
					}
				},
				_uploadComplete: function(event) {
					var sequence = event.target.responseText;
					this.currentFileinfo.complete = true;
					this.currentFileinfo.sequence = sequence;
					this.currentFileinfo = null;
					//记录上传完成的文件名
					this.completednames.push(sequence);
					//调用父页面的方法
					if(this.callback != "") {
						window.parent.postMessage({
						    "seq": sequence
						},'*');
						//eval("window.parent." + this.callback + "('" + sequence + "')");	
					}
					//上传完成后，继续上传其他文件
					this._upload();
				},
				_uploadCanceled: function(event) {
					//取消上传后，继续上传其他文件
					this._upload();
				},
				removeFileInfo: function(fileinfo) {
					//确定要删除的文件信息在数组中的位置
					var removeIndex = -1;
					for(var i = 0; i < this.fileinfos.length; i++) {
						if(fileinfo == this.fileinfos[i]) {
							removeIndex = i;
							break;
						}
					}
					//删除文件信息
					this.fileinfos.splice(removeIndex, 1);
					//如果已经上传过了，那么计数器-1
					if(removeIndex < this.count) {
						this.count--;	
					}
					//如果删除的文件正在上传，则停止上传
					if(this.currentFileinfo == fileinfo) {
						this.currentFileinfo = null;
						this.request.abort();
					} else if(fileinfo.complete) {
						// 如果已经上传完成，删除调用删除文件服务接口
						var request = new XMLHttpRequest();
						var url = this.deleteURL + "/" + fileinfo.sequence;
						request.open("GET", url);
						request.send();
					}
				},
				clear: function() {
					while(this.fileinfos.length > 0) {
						this.removeFileInfo(this.fileinfos[0]);
					}
				},
				
			}
		});
		
		Vue.component('file-info', {
			props: ['file'],
			data: function () {
			  return {
			  }
			},
			template: '#file-info',
			computed:{
			  filesize: function() {
				  var file = this.file;
				  if (file.size > 1024 * 1024) {
					fileSize = (Math.round(file.size * 100 / (1024 * 1024)) / 100) + 'MB';
				  } else {
					fileSize = (Math.round(file.size * 100 / 1024) / 100) + 'KB';
				  }
				  return fileSize;
			  }
			}
		});
		
		
		
	</script>
	
	<script type="x-template" id="file-info">
		<div class="fileinfoBlock">
			<div class="icon"><img src="/img/file.png"></div>
			<div>
				<div class="center">
					<div>
						<div class="filename">{{file.name}}</div>
						<div class="operater"><a v-on:click="$emit('remove', file)">删除</a></div>
						<div style="clear: both;"></div>
					</div>
					<div class="filesize">{{filesize}} {{file.percentComplete == 100 ? '上传完成' : ''}}</div>
					<progress v-if="file.percentComplete > 0" v-bind:value='file.percentComplete' max='100'></progress>
				</div>
				<div style="clear: both;"></div>
			</div>
		</div>
	</script>
</body>
</html>